package com.z_talk.client.core;

import com.z_talk.client.config.PropertiesUtil;
import com.z_talk.client.view.LoginView;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;

import javax.swing.*;

public class ClientMain {

    public static void init(){
        String host = PropertiesUtil.configProp.getProperty("serverHost");
        int port = Integer.parseInt(PropertiesUtil.configProp.getProperty("serverPort"));
        // 创建一个NIO循环组
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            // 创建通信管道 channel
            bootstrap.group(group).channel(NioSocketChannel.class)
                    // 配置消息处理器
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast("decoder",new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                            pipeline.addLast("encoder",new ObjectEncoder());
                            pipeline.addLast(new ClientHandler());
                        }
                    });
            System.out.println( " netty client start ");
            ClientSender clientSender = ClientSender.getInstance();
            clientSender.setBootstrap(bootstrap);
            clientSender.connect(host,port);
            new LoginView();
            clientSender.listen();
        } catch (Exception e){
            JOptionPane.showMessageDialog(new JFrame(),
                    "连接服务器失败,请检查!","服务器未连上", JOptionPane.ERROR_MESSAGE);//否则连接失败
            System.exit(0);
        }finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        init();
    }
}
